
/**
 * 复选框组件2.1 by Ciding QQ842601155
 * 2019-06-13
 * 参数dom 传入按钮id|class
 * 参数title 弹窗标题
 * 参数confObj 数组例如：[
		{url:'querydaibiaoxinbyidorname2',type:'POST',fieldId:'rdSparefield21',fieldName:'按区县',showFieldName:'rdSparefield4',hideFieldId:'rdId'},
		{url:'querydaibiaoxinbyidorname2',type:'POST',fieldId:'rdSparefield20',fieldName:'按职务',showFieldName:'rdSparefield4',hideFieldId:'rdId'},
		{url:'querydaibiaoxinbyidorname2',type:'POST',fieldId:'rdSparefield2',fieldName:'按界别',showFieldName:'rdSparefield4',hideFieldId:'rdId'},
		{url:'querydaibiaoxinbyidorname2',type:'POST',fieldId:'rdSparefield16',fieldName:'按学历',showFieldName:'rdSparefield4',hideFieldId:'rdId'}
	]
	url：数据源url
	type：请求方式
	fieldId：组件要存取的id
	fieldName：要存取或显示的name
	showFieldName：显示的分类name
	hideFieldId：模板要使用的唯一id
 * 参数checkedIds 传入选中数组的ids逗号分割即可 (与下面顺序可以不用对应)
 * 参数checkedNames 传入选中数组的names逗号分割即可 (与上面顺序可以不用对应)
 * fn callback
 * return 选中数组对象
 * 请慎重修改，需考虑扩展性和维护性进行合理修改。
 * @param exports
 * @returns
 */
layui.define(['jquery', 'form', 'layer', 'layedit', 'laytpl', 'element'],function(exports){
	
	  var $ = layui.$
	  ,form = layui.form
	  ,layer = layui.layer
	  ,laydate = layui.laydate
	  ,laytpl = layui.laytpl
	  ,element = layui.element;

	var loading;//loading
	
	var win;//window
	
	var rmItem = false;//是否开启删除item
	
	var userCss={
		userItem:'style="margin: 8px 5px 0px 0; padding: 0 2px 0 4px;cursor: default;"',
		userItemclose:'style="cursor: pointer;color: #aaaaaa;vertical-align: middle;display:'+(rmItem?'inline-block':'none')+';" \
						onMouseOver="this.style.color=\'#eb4f38\'" \
						onMouseOut="this.style.color=\'#aaaaaa\'"'
	}

	_cidingLayCheck= function(dom,title,confObj,checkedIds,checkedNames,fn){
		
		if(!confObj||confObj.length==0){
			layer.msg('组件参数不正确！');
			return false;
		}
		
		var me = this;
		
		var mk = dom.replace('.','').replace('#','');//唯一标识
		
		var _btnGroupHtml = '';//按钮组
   		
   		var limiting='';//定时器
   		
   		me.o={};//数据对象
   		
   		me.o.hideCount = 60;//必须是6的倍数

   		me.results = [];//所选checked数组
   		
   		setChecked();//选中初始化数据
   		
   		//原始选中数据初始化
   		function setChecked(){
   			if(checkedNames&&checkedNames!=''){
				var showSpans='';
				$.each(checkedNames.split(','),function(index,item){
					showSpans+='<span class="layui-badge layui-bg-gray" '+userCss.userItem+'>'+item+' <i class="layui-icon layui-icon-close-fill removeItem" '+userCss.userItemclose+'></i></span>';
				});
				showSpans = '<div class="checkedusers'+mk+'" style="width: 600px;margin: 0 auto;">'+showSpans+'</div>';//margin-left:'+$(dom).offset().left+'px;
				if($('.checkedusers'+mk).length==0){
					$(dom).after(showSpans);
				}else{
					$(dom).next().replaceWith(showSpans);
				}
   			}
   		}
   		
		//主窗口
		$(dom).on('click',function(){
			win = layer.open({
				type: 1,
				title: title||'选择',
			 	shadeClose: true,
			  	area: ['650px', '480px'], //宽高
				content: $('#choose_tpl').html(),
				success: function(layero, index){
					
					//组件内部初始化赋值
					if($('.select_com_ids'+mk).length>0&&$('.select_com_names'+mk).length>0){
						var ids = $('.select_com_ids'+mk).val().split(',');
						var names = $('.select_com_names'+mk).val().split(',');
						for(var i=0;i<ids.length;i++){
							me.results.push(JSON.stringify({id:ids[i]+'',name:names[i]}));
						}
					}
					//生成按钮组、框架渲染
					_btnGroupHtml = _initData(confObj);
					_renderFrame(me.o);
				},
				end: function(){
					//重置参数
					me.o={};
			   		me.o.hideCount = 60;
			   		me.results = [];
				}
			});
		});
		
		//数据初始化：获取并生成内部数据 和 按钮组
		function _initData(confObj,checkedNum){
			
			var index =checkedNum||0;
			var url = confObj[index].url;
			var param = confObj[index].param;
			var type = confObj[index].type;
			
			me.o.targetShowFieldName = confObj[index].showFieldName;
			me.o.targetHideFieldId = confObj[index].hideFieldId;
			
			_reqData(url,param,type,function(data){
		  	  if(data){
				var ow = new Object();
				for(var i=0;i<data.length;i++){
					if(ow[data[i][confObj[index].fieldId]]){
						ow[data[i][confObj[index].fieldId]].push(data[i]);
					}else{
						ow[data[i][confObj[index].fieldId]] = [];
						ow[data[i][confObj[index].fieldId]].push(data[i]);
					}
				}
				
				//基础数据获取
				me.o.data=ow;
				
				//已选数据
				if($('.select_com_names'+mk).length==0&&checkedIds&&checkedIds.split(',').length>0){
					//入参选中数据特殊处理，首次传入原始数据在此处处理
					$.each(checkedIds.split(','),function(k,v){
						$.each(me.o.data,function(idx,item){
							$.each(item,function(key,value){
								if(value[me.o.targetHideFieldId]==v){
									value.checked = true;
									me.results.push(JSON.stringify({id:value[me.o.targetHideFieldId]+'',name:value[me.o.targetShowFieldName]}));
								}
							});
						});
					});
					checkedIds=null;
				}else{
					if(me.results&&me.results.length>0){
						$.each(me.results,function(k,v){
							$.each(me.o.data,function(idx,item){
								$.each(item,function(key,value){
									if(value[me.o.targetHideFieldId]==JSON.parse(v).id && value[me.o.targetShowFieldName]==JSON.parse(v).name){
										value.checked = true;
									}
								});
							});
						});
					}
				}
				
		  	  }
		    });

			//设置分组按钮
            var btn_tpl = $('#btn_group_tpl').html();

			//关闭loading
			layer.close(loading);
			
			//返回按钮组渲染结果
    		return laytpl(btn_tpl).render(confObj);
		}
		
		//对象拷贝
		function _deepCopy(obj) {
	      var result = Array.isArray(obj) ? [] : {};
	      for (var key in obj) {
	        if (obj.hasOwnProperty(key)) {
	          if (typeof obj[key] === 'object') {
	            result[key] = _deepCopy(obj[key]);   //递归复制
	          } else {
	            result[key] = obj[key];
	          }
	        }
	      }
	      return result;
	    }
		
		//框架渲染
		function _renderFrame(data,key){
			
            var user_tpl = $('#choose_tpl').html();

    		laytpl(user_tpl).render(data, function(html){
    			html = $(html).css('display','block');

    			//更换checked并渲染
				$("#choose_dom").replaceWith(html);
				form.render('checkbox');
				
				//设置全选并重新渲染
				if($('.layui-collapse [lay-filter="checkPartAll"]').next('.layui-form-checked').length==$('.layui-collapse [lay-filter="checkPartAll"]').length){
					$('.searchAll').prop("checked", true);
				}else{
					$('.searchAll').prop("checked", false);
				}
				form.render('checkbox');
				
				//设置按钮组
				$('.searchAll').before(_btnGroupHtml);

				//设置高亮结果
				if(key&&key!=''){
					$('.layui-icon-ok').prev().each(function(idx,item){
						$(item).html($(item).text().replace(key,'<span style="color:red;padding: 0;">'+key+'</span>'));
					});
				}
				
				//监听item选中
				form.on('checkbox(status)', function(obj){
					
				    var data = obj.elem;

					var id =  $(obj.elem).attr('name').replace('like_','');
					
					var name =  $(obj.elem).attr('title');
					
					if(obj.elem.checked){
						me.results.push(JSON.stringify({id:id+'',name:name}));
					}else{
						me.results.remove(JSON.stringify({id:id+'',name:name})); 
					}

					if($(this).parents('.layui-form-item').find('.layui-form-checked').length!=$(this).parents('.layui-form-item').find('[type="checkbox"]').length){
						$(this).parents('.layui-colla-content').prev().find('[lay-filter="checkPartAll"]').prop("checked", false);
					}else{
						$(this).parents('.layui-colla-content').prev().find('[lay-filter="checkPartAll"]').prop("checked", true);
					}
					
	                form.render('checkbox');

	                if($('.layui-collapse [lay-filter="checkPartAll"]').next('.layui-form-checked').length!=$('.layui-collapse [lay-filter="checkPartAll"]').length){
						$('.searchAll').prop("checked", false);
					}else{
						$('.searchAll').prop("checked", true);
					}
					
					if(me.o){
						$.each(me.o.data,function(idx,item){
							$.each(item,function(key,value){
								if(value[me.o.targetHideFieldId]==id && value[me.o.targetShowFieldName]==name){
									value.checked = obj.elem.checked?true:false;
									return false;
								}
							});
						});
					}
					
	                form.render('checkbox');

				});
				
				//监听part-all
				form.on('checkbox(checkPartAll)', function (obj) {
					layui.stope(window.event);

		            var a = obj.elem.checked;
		            if (a == true) {
		                $(this).parent().next().find('[type="checkbox"]').prop("checked", true);
		                form.render('checkbox');
		                if(!$(this).parent().next().hasClass('layui-show')){
		                	$(this).parent().click();
		                }
		            } else {
		            	$(this).parent().next().find('[type="checkbox"]').prop("checked", false);
		            }
		            
		            $.each($(this).parent().next().find('[type="checkbox"]'),function(i,v){

						var id =  $(v).attr('name').replace('like_','');
						var name =  $(v).attr('title');
						
						if(obj.elem.checked){
							me.results.remove(JSON.stringify({id:id+'',name:name})); 
							me.results.push(JSON.stringify({id:id+'',name:name}));
						}else{
							me.results.remove(JSON.stringify({id:id+'',name:name})); 
						}
						
						if(me.o){
							$.each(me.o.data,function(idx,item){
								$.each(item,function(key,value){
									if(value[me.o.targetHideFieldId]==id && value[me.o.targetShowFieldName]==name){
										value.checked = obj.elem.checked?true:false;
										return false;
									}
								});
							});
						}
		            });
	                form.render('checkbox');
	                
					if($('.layui-collapse [lay-filter="checkPartAll"]').next('.layui-form-checked').length==$('.layui-collapse [lay-filter="checkPartAll"]').length){
						$('.searchAll').prop("checked", true);
					}else{
						$('.searchAll').prop("checked", false);
					}
	                form.render('checkbox');
			 
			    });
				
				//展开收起
				$('.slideBlock').unbind('click').bind('click',function(e){
		            if($(this).find('i').hasClass('layui-icon-down')){
		    			$(this).html('<i class="layui-icon layui-icon-up"></i>').parent().prev().slideDown(300);
		            }else{
		    			$(this).html('<i class="layui-icon layui-icon-down"></i>').parent().prev().slideUp(300);
		            }
		        });

				//按钮组事件
				$('.btn_group').unbind('click').bind('click',function(e) {
					var num = $(this).attr('data-num');
					loading = layer.load(1, {
					  shade: [0.1,'rgb(0, 0, 0)'],
					  success: function(layero, index){
						  setTimeout(function(){
							  _btnGroupHtml = _initData(confObj,num);
							  _renderFrame(me.o);
						  },200);
					  }
					});
				});

				//关闭事件
				$('#rd_no').unbind('click').bind('click',function(e){
					e.preventDefault();
					layer.close(win);
				});

				//确定事件
				$('#rd_yes').unbind('click').bind('click',function(e){
					e.preventDefault();
					
					//创建hidden承载
					if($('.select_com_ids'+mk).length==0&&$('.select_com_names'+mk).length==0){
						$(dom).before('<input type="hidden" class="select_com_ids'+mk+'" name="select_com_ids"></input>');
						$(dom).before('<input type="hidden" class="select_com_names'+mk+'" name="select_com_names"></input>');
					}
					
					//数据重组
					var ids = '',names='',returnData=[],showSpans='';

					$.each(me.results,function(index,item){
						var user = JSON.parse(item);
						returnData.push(user);
						showSpans+='<span class="layui-badge layui-bg-gray" '+userCss.userItem+'>'+user.name+' <i class="layui-icon layui-icon-close-fill" '+userCss.userItemclose+'></i></span>';
						ids+=user.id+',';
						names+=user.name+',';
					});
					
					ids= ids.substring(0,ids.length-1);
					names= names.substring(0,names.length-1);
					
					$('.select_com_ids'+mk).val(ids);
					$('.select_com_names'+mk).val(names);

					showSpans = '<div class="checkedusers'+mk+'" style="width: 600px;margin: 0 auto;">'+showSpans+'</div>';//margin-left:'+$(dom).offset().left+'px;

					if($('.checkedusers'+mk).length==0){
						$(dom).after(showSpans);
					}else{
						$('.checkedusers'+mk).replaceWith(showSpans);
					}
					
					//callback
					if(fn){
						fn(returnData);
						layer.close(win);
					}
				});

				
				//输入中文拼音在输入框input事件问题
				var flag = true;
				$(".search_inline input").on('compositionstart',function(){
		            flag = false;
		        })
		        $(".search_inline input").on('compositionend',function(){
		            flag = true;
		        })
		        
				//搜索监听输入
				$(".search_inline input").unbind('keydown').val(key).on("keydown",function(e){
					//完善版联系作者CIDING_QQ_842601155
		        }).focus();
			});
    		
    		//渲染
			element.render('collapse');
		}
   	}

	$(document).on('click', '.removeItem',function(){
		var username = $(this).parent().text().trim();
		/*待完善
		console.log($(this),userData.data);*/
	});
	
	function _reqData(reqUrl,ObjData,type,callBack){
		$.ajax({
	      url: reqUrl,
	      data:ObjData,
	      async:false,
	      type : type,
	      success: function (data) {
	    	  if(data){
	    		  if(callBack){
	    			  callBack(data);
	    		  }
	    	  }
	      }
		});
	}
	
	Array.prototype.indexOf = function(val) { 
		for (var i = 0; i < this.length; i++) { 
			if (this[i] == val) return i; 
		} 
		return -1; 
	}; 
	Array.prototype.remove = function(val) { 
		var index = this.indexOf(val); 
		if (index > -1) { 
			this.splice(index, 1); 
		} 
	}; 

	
	exports('cidingLayCheck', {
		initCheck: _cidingLayCheck
	});
	
});
